// modules =================================================
var express        = require('express');
var app            = express();
var mongoose       = require('mongoose');
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');
var connectionPool = require('express-myconnection');
var fileUpload     = require('express-fileupload');
var http           = require("http");
var webSocketServer = require("websocket").server;
// configuration ===========================================
	
// config files
// var db = require('./config/db');
// if(db){
//   console.log("success to connect the database!");
// }

var port = process.env.PORT || 3000; // set our port
// mongoose.connect(db.url); // connect to our mongoDB database (commented out after you enter in your own credentials)

const server = http.createServer(app);
var mysql = require("mysql");

var dbOptions ={
	connectionLimit:20,
	host : '192.168.1.15',
	user:'root',
	password:'rootroot/',
	port:3306,	
	database:'OrderSystem'
};

var pool = connectionPool(mysql,dbOptions,'pool');
app.use(pool);
console.log(pool);

var wsServer = new webSocketServer({
	httpServer:server,
	autoAcceptConnections:true
});

wsServer.on('connect', (connection) => {
	console.log("success to connect~");
    connection.on('message', (message) => {     //收消息
        console.log(">> message", message);
        if (message.utf8Data==='goods') {
					 var connectionSql = mysql.createConnection(dbOptions);
					 //console.log(pool);
            // pool.getConnection(function(err,conn){
						// if(err){
						// 	console.log("Failed to connect");
						// };
						connectionSql.query("select * from menu_list",function(err,rows){
							if(err){
								console.log(err);
							}else{
								var menu_data = JSON.stringify(rows);
								connection.send(menu_data);
							}
						});
						console.log('test');
						connectionSql.end();
        }
        if(message.utf8Data==='goodsList'){
					var connectionSql = mysql.createConnection(dbOptions);
					connectionSql.query("SELECT * FROM type_list",function(err,rows){
						if(err){
							console.log("failed to connect to mysql");
						}else{
							var type_data = JSON.stringify(rows);
							connection.send(type_data);
						}
					})
        }
        if(message.utf8Data==='form'){
         		var connectionSql = mysql.createConnection(dbOptions);
					 connectionSql.query("SELECT * FROM order_list",function(err,rows){
						if(err){
							console.log("failed to connect to mysql");
						}else{
							var type_data = JSON.stringify(rows);
							connection.send(type_data);
						}
					})
        }
    });

    connection.on('close', (reasonCode, description) => {
        console.log('[' + (new Date()) + ']Peer' + connection.remoteAddress + 'disconnected.');
    });
});
// connectionPool.on('connection',function(connection){
	
// })
// connection.connect(function(err){
// 	if(err){
// 		console.log('error connecting: '+ err.stack);
// 		return;
// 	}
// 	console.log('connected as id' +connection.threadId);
// });

// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json 
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded

app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(fileUpload());
// routes ==================================================
require('./app/ordersystem.server.routes')(app); // pass our application into our routes
// start app ===============================================
server.listen(port);	
console.log('Magic happens on port ' + port); 			// shoutout to the user

exports = module.exports = app; 						// expose app